<script lang="ts" setup>
import type { WeddingOrder, ServiceItem, OrderTimelineItem } from '#/api/wedding';
import { useVbenModal } from '@vben/common-ui';
import {
  Descriptions,
  DescriptionsItem,
  Table,
  Tag,
  Tabs,
  TabPane,
  Timeline,
  TimelineItem,
  Button,
  message,
} from 'ant-design-vue';
import { ref } from 'vue';
import {
  getOrder,
  getOrderTimeline,
  getPaymentRecords,
  confirmOrder,
  cancelOrder,
  payOrder,
} from '#/api/wedding';
import { getOrderServiceItems } from '#/api/wedding/weddingorder';
import { getOrderStatusText, getOrderStatusColor } from './data';

const orderData = ref<WeddingOrder>();
const serviceItems = ref<ServiceItem[]>([]);
const timelineData = ref<OrderTimelineItem[]>([]);
const paymentRecords = ref<any[]>([]);
const loading = ref(false);

const emit = defineEmits(['success']);

const serviceItemColumns = [
  { title: '服务类型', dataIndex: 'serviceType', key: 'serviceType', width: 100 },
  { title: '资源编号', dataIndex: 'resourceCode', key: 'resourceCode', width: 140 },
  { title: '资源名称', dataIndex: 'resourceName', key: 'resourceName' },
  { title: '单价', dataIndex: 'price', key: 'price', width: 120 },
  { title: '数量', dataIndex: 'quantity', key: 'quantity', width: 80 },
  { title: '小计', dataIndex: 'subtotal', key: 'subtotal', width: 120 },
];

const paymentColumns = [
  { title: '支付金额', dataIndex: 'paymentAmount', key: 'paymentAmount', width: 120 },
  { title: '支付方式', dataIndex: 'paymentMethod', key: 'paymentMethod', width: 120 },
  { title: '支付时间', dataIndex: 'paymentTime', key: 'paymentTime', width: 180 },
  { title: '交易号', dataIndex: 'transactionNo', key: 'transactionNo' },
];

// 确认订单
const handleConfirm = async () => {
  if (!orderData.value) return;
  
  loading.value = true;
  try {
    await confirmOrder(orderData.value.orderId);
    message.success('订单已确认');
    await loadOrderData();
    emit('success');
  } finally {
    loading.value = false;
  }
};

// 取消订单
const handleCancel = async () => {
  if (!orderData.value) return;
  
  loading.value = true;
  try {
    await cancelOrder(orderData.value.orderId, '客户取消');
    message.success('订单已取消');
    await loadOrderData();
    emit('success');
  } finally {
    loading.value = false;
  }
};

const loadOrderData = async () => {
  if (!orderData.value) return;
  
  const orderId = orderData.value.orderId;
  
  // 重新加载订单详情
  orderData.value = await getOrder(orderId);
  
  // 加载服务项
  serviceItems.value = await getOrderServiceItems(orderId);
  
  // 加载时间轴
  timelineData.value = await getOrderTimeline(orderId);
  
  // 加载支付记录
  paymentRecords.value = await getPaymentRecords(orderId);
};

const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<WeddingOrder>();
    if (!data?.orderId) {
      return;
    }

    modalApi.lock();
    try {
      orderData.value = await getOrder(data.orderId);
      await loadOrderData();
    } finally {
      modalApi.unlock();
    }
  },
});
</script>

<template>
  <Modal title="订单详情" width="1000px" :show-ok-btn="false">
    <Tabs default-active-key="1" v-if="orderData">
      <TabPane key="1" tab="基本信息">
        <Descriptions bordered :column="2">
          <DescriptionsItem label="订单号">
            {{ orderData.orderId }}
          </DescriptionsItem>
          <DescriptionsItem label="订单状态">
            <Tag :color="getOrderStatusColor(orderData.status)">
              {{ getOrderStatusText(orderData.status) }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="客户姓名">
            {{ orderData.customerName }}
          </DescriptionsItem>
          <DescriptionsItem label="客户电话">
            {{ orderData.customerPhone }}
          </DescriptionsItem>
          <DescriptionsItem label="婚期">
            {{ orderData.weddingDate }}
          </DescriptionsItem>
          <DescriptionsItem label="创建时间">
            {{ orderData.createTime }}
          </DescriptionsItem>
          <DescriptionsItem label="总金额">
            <span class="text-red-500 font-bold text-lg">
              ¥{{ orderData.totalAmount }}
            </span>
          </DescriptionsItem>
          <DescriptionsItem label="已付金额">
            <span class="text-green-500 font-semibold">
              ¥{{ orderData.paidAmount }}
            </span>
          </DescriptionsItem>
          <DescriptionsItem label="优惠金额">
            ¥{{ orderData.discountAmount || 0 }}
          </DescriptionsItem>
          <DescriptionsItem label="待付金额">
            <span class="text-orange-500 font-semibold">
              ¥{{ orderData.totalAmount - orderData.paidAmount }}
            </span>
          </DescriptionsItem>
          <DescriptionsItem label="备注" :span="2">
            {{ orderData.remarks || '无' }}
          </DescriptionsItem>
        </Descriptions>

        <!-- 操作按钮 -->
        <div class="mt-4 flex space-x-2">
          <Button
            v-if="orderData.status === 'DRAFT'"
            type="primary"
            @click="handleConfirm"
            :loading="loading"
          >
            确认订单
          </Button>
          <Button
            v-if="orderData.status === 'DRAFT' || orderData.status === 'CONFIRMED'"
            danger
            @click="handleCancel"
            :loading="loading"
          >
            取消订单
          </Button>
        </div>
      </TabPane>

      <TabPane key="2" tab="服务项">
        <Table
          :dataSource="serviceItems"
          :columns="serviceItemColumns"
          :pagination="false"
          size="small"
        />
      </TabPane>

      <TabPane key="3" tab="支付记录">
        <Table
          :dataSource="paymentRecords"
          :columns="paymentColumns"
          :pagination="false"
          size="small"
        />
      </TabPane>

      <TabPane key="4" tab="订单时间轴">
        <Timeline>
          <TimelineItem
            v-for="item in timelineData"
            :key="item.id"
          >
            <div class="font-medium">{{ item.action }}</div>
            <div class="text-sm text-gray-600">{{ item.description }}</div>
            <div class="text-xs text-gray-400 mt-1">
              {{ item.operator }} · {{ item.operateTime }}
            </div>
          </TimelineItem>
        </Timeline>
      </TabPane>
    </Tabs>
  </Modal>
</template>

